package com.fengye.middleware.redis.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * RedisTemplate 自定义注入配置的属性主要是缓存中Key与Value的<strong>序列化策略</strong>
 * <br>
 * 在Spring Boot项目中使用Redis进行相关业务操作之前，将自定义的RedisTemplate与StringRedisTemplate组件的代码注入到项目中
 * @author sky
 * @date 2021/06/07 21:25
 */
@Configuration
public class RedisCommonConfig {

    private final RedisConnectionFactory connectionFactory;

    public RedisCommonConfig(RedisConnectionFactory connectionFactory){
        this.connectionFactory = connectionFactory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        // 设置Redis连接工厂
        redisTemplate.setConnectionFactory(connectionFactory);

        // TODO: 指定Key序列化策略为String序列化，Value为JDK自带的序列化策略
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());

        // TODO: 指定hashKey序列化策略为String序列化 -- 针对hash散列存储
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());

        return redisTemplate;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        // TODO: 采用默认配置即可 - 后续有自定义配置在此处添加
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(connectionFactory);
        return stringRedisTemplate;
    }


}
